library(tidyverse)
library(raster)
library(sf)

#wd <- "C:\\Users\\msant\\Dropbox\\Sugarcane Offline Data\\mapbiomas"
wd <- "D:\\Dropbox\\Sugarcane Offline Data\\MapBiomas"
setwd(wd)

cerrado   <- raster("COLECAO_4_1_ANUAL_CERRADO_CERRADO-2004.tif")
atlantica <- raster("COLECAO_4_1_DOWNLOADS_COLECOES_ANUAL_MATAATLANTICA_MATAATLANTICA-2004.tif")
amazon    <- raster("COLECAO_4_1_DOWNLOADS_COLECOES_ANUAL_AMAZONIA_AMAZONIA-2004.tif")

grid <- st_read(dsn = '..\\GridBuild\\CanasatData.gdb', layer = 'G1kmMiR')
st_transform(grid, 4326)

atlantica_g <- extract(atlantica, grid)
cerrado_g   <- extract(cerrado, grid)
amazon_g    <- extract(amazon, grid)

grid$atlantica <- atlantica_g
grid$cerrado   <- cerrado_g
grid$amazon    <- amazon_g

grid$atlantica[is.na(grid$atlantica)] <- 0
grid$cerrado[is.na(grid$cerrado)] <- 0
grid$amazon[is.na(grid$amazon)] <- 0

grid$mb_uso_detalhe <- 0

grid$mb_uso_detalhe[grid$atlantica>0] <- grid$atlantica[grid$atlantica>0]
grid$mb_uso_detalhe[grid$cerrado>0] <- grid$cerrado[grid$cerrado>0]
grid$mb_uso_detalhe[grid$amazon>0] <- grid$amazon[grid$amazon>0]

grid$mb_bioma <- 0
grid$mb_bioma[grid$atlantica>0] <- 1
grid$mb_bioma[grid$cerrado>0] <- 2
grid$mb_bioma[grid$amazon>0] <- 3

grid$cerrado <- NULL
grid$atlantica <- NULL
grid$amazon <- NULL
grid$Shape <- NULL
grid <- as_tibble(grid)
write_csv(grid, '..\\GridBuild\\Tables\\G1kmMiRMapbiomas.csv')